# 音频转文字服务主应用

import os
import asyncio
from contextlib import asynccontextmanager
from fastapi import FastAPI, Depends, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from .api.router import router as api_router
from .core.config import settings
from .core.monitoring import performance_monitor
import logging

logger = logging.getLogger(__name__)

@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    应用生命周期管理
    """
    # 启动时的初始化
    logger.info("正在启动音频转文字服务...")
    
    # 初始化监控系统
    if settings.MONITORING_ENABLED:
        logger.info("正在启动监控系统...")
        try:
            # 启动系统指标收集
            performance_monitor.start_system_metrics_collection()
            logger.info("监控系统启动成功")
        except Exception as e:
            logger.error(f"监控系统启动失败: {str(e)}")
    else:
        logger.info("监控功能已禁用")
    
    logger.info("音频转文字服务启动完成")
    
    yield
    
    # 关闭时的清理
    logger.info("正在关闭音频转文字服务...")
    
    # 停止监控系统
    if settings.MONITORING_ENABLED:
        logger.info("正在停止监控系统...")
        try:
            performance_monitor.stop_system_metrics_collection()
            # 导出最终的监控数据
            if performance_monitor.tasks or performance_monitor.completed_tasks:
                final_export_path = os.path.join(
                    os.path.dirname(settings.METRICS_EXPORT_PATH),
                    "final_monitoring_export.json"
                )
                performance_monitor.export_metrics(final_export_path)
                logger.info(f"最终监控数据已导出到: {final_export_path}")
            logger.info("监控系统已停止")
        except Exception as e:
            logger.error(f"停止监控系统时出错: {str(e)}")
    
    logger.info("音频转文字服务已关闭")

def create_application() -> FastAPI:
    """
    创建并配置FastAPI应用
    """
    application = FastAPI(
        title=settings.PROJECT_NAME,
        description=settings.PROJECT_DESCRIPTION,
        version=settings.VERSION,
        docs_url="/docs",
        redoc_url="/redoc",
        lifespan=lifespan,
    )

    # 配置CORS
    cors_origins = settings.cors_origins_list
    if cors_origins and cors_origins[0] == "*":
        # 如果是通配符，直接使用 "*"
        application.add_middleware(
            CORSMiddleware,
            allow_origins=["*"],
            allow_credentials=True,
            allow_methods=["*"],
            allow_headers=["*"],
        )
    else:
        # 否则使用配置的具体域名
        application.add_middleware(
            CORSMiddleware,
            allow_origins=cors_origins,
            allow_credentials=True,
            allow_methods=["*"],
            allow_headers=["*"],
        )

    # 添加全局异常处理器
    @application.exception_handler(HTTPException)
    async def http_exception_handler(request: Request, exc: HTTPException):
        """
        全局HTTP异常处理器
        """
        return JSONResponse(
            status_code=exc.status_code,
            content={"detail": exc.detail}
        )

    @application.exception_handler(Exception)
    async def general_exception_handler(request: Request, exc: Exception):
        """
        全局异常处理器
        """
        # 记录详细的错误信息
        import traceback
        error_traceback = traceback.format_exc()
        logger.error(f"未处理的异常: {str(exc)}")
        logger.error(f"请求URL: {request.url}")
        logger.error(f"请求方法: {request.method}")
        logger.error(f"错误堆栈: {error_traceback}")
        
        return JSONResponse(
            status_code=500,
            content={"detail": "服务器内部错误，请稍后重试"}
        )

    # 添加API路由
    application.include_router(api_router, prefix=settings.API_PREFIX)

    @application.get("/", tags=["健康检查"])
    async def health_check():
        """
        健康检查接口
        """
        return {"status": "healthy", "service": "audio-to-text"}

    return application

# 创建应用实例
app = create_application()

if __name__ == "__main__":
    import uvicorn
    port = int(os.getenv("PORT", 8000))
    uvicorn.run("app.main:app", host="0.0.0.0", port=port, reload=True)